package _4TCPChat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class TCPChatClient extends Thread 
{
	public final static String HOST = "127.0.0.1";
	public final static int PORT = 7777;
	
	ChatClientFrame ccFrame;
	OutputStream out;
	
	public void send(String msg)
	{
		try {
			out.write(msg.getBytes());
		} catch (IOException e) {
			ccFrame.showMsg("网络发送出错"+e.getMessage());
		}
	}

	@Override
	public void run() {

		// 1. 新建Socket
		ccFrame.showMsg("客户端:连接服务器" + HOST + ":" + PORT);
		Socket s;
		try {
			s = new Socket(HOST,PORT);
		} catch (UnknownHostException e) {
			ccFrame.showMsg("HOST无法解析");
			return;
		} catch (IOException e) {
			ccFrame.showMsg("HOST无法连接");
			return;
		}

		// 2.
		ccFrame.showMsg("已连上服务器");
		try {
			InputStream in = s.getInputStream();
			out = s.getOutputStream();
			
			// 3. 读取信息
			// 接收服务器发来的信息
			while(true)
			{
				byte[] buf = new byte[1024];
				int len = in.read(buf); // 会卡在这
				String msg = new String(buf, 0, len);
				ccFrame.showMsg("服务器发来:" + msg);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}